//
//  NewUserRegisterVC.m
//  leyitui
//
//  Created by 王大江 on 17/10/17.
//  Copyright © 2017年 xinleyi. All rights reserved.
//

#import "NewUserRegisterVC.h"
#import "NSString+Check.h"
#import "PGTabBarController.h"

@interface NewUserRegisterVC ()<UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UITextField *telPhoneTF;
@property (weak, nonatomic) IBOutlet UITextField *msgCodeTF;
@property (weak, nonatomic) IBOutlet UITextField *passWdTF;

@property (weak, nonatomic) IBOutlet UIButton *sendMsgBtn;
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;

@property (weak, nonatomic) IBOutlet UIButton *agreeProtocolBtn;



@property(nonatomic,assign)int time; //倒计时时间

@end

@implementation NewUserRegisterVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configSubUI];
//    // 设置导航控制器的代理为self
//    self.navigationController.delegate = self;
    [self setNavigationStyle];
    
}

//#pragma mark - UINavigationControllerDelegate
//- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
//    // 判断要显示的控制器是否是自己
//    BOOL isShowHomePage = [viewController isKindOfClass:[self class]];
//    [self.navigationController setNavigationBarHidden:isShowHomePage animated:YES];
//}

#pragma 设置导航栏样式 - 去背景、去底部线条、状态栏白色
- (void)setNavigationStyle {
    //去掉背景图片
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    //去掉底部线条
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    self.navigationController.navigationBar.barStyle = UIStatusBarStyleLightContent;
}

-(void)configSubUI {
    self.telPhoneTF.keyboardType = UIKeyboardTypeNumberPad;
    self.msgCodeTF.keyboardType = UIKeyboardTypeNumberPad;
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(back) image:@"back" highImage:@"back"];
    
}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 利用touchbegin事件实现点空白处收起键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.telPhoneTF resignFirstResponder];
    [self.msgCodeTF resignFirstResponder];
    [self.passWdTF resignFirstResponder];
}

#pragma mark 发送验证码
- (IBAction)sendMsgCodeBtn:(id)sender {
    [self.view endEditing:YES];
    if (![self.telPhoneTF.text checkPhoneNumInput] ) {
        [MBProgressHUD showError:@"请输入正确的手机号码"];
        return;
    }
    
    NSMutableDictionary *para = [[NSMutableDictionary alloc] init];
    para[@"mobile"] = self.telPhoneTF.text;
    [XYNetworking POST:@"api/getCode" baseURL:LYT_BASE_URL params:para success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary * dict = (NSDictionary*)responseObject;
        LoLog(@"%@",dict);
        if ([dict[@"code"] intValue] == 0) {
            [MBProgressHUD showSuccess:@"验证码发送成功,注意查收!"];
            self.sendMsgBtn.userInteractionEnabled = NO;  //发送成功按钮先禁掉
            self.time = 60;
            [self.sendMsgBtn setTitle:@"60S" forState:UIControlStateNormal];
            [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeaction:) userInfo:self.sendMsgBtn repeats:YES];
        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        [MBProgressHUD showError:@"请检查网络"];
    }];
}

-(void)timeaction:(NSTimer*)timer {
    UIButton *sendMsgBtn = timer.userInfo;
    [sendMsgBtn setTitle:[NSString stringWithFormat:@"%ldS",(long)self.time--] forState:UIControlStateNormal];
    if (self.time < -1) {
        sendMsgBtn.userInteractionEnabled = YES;
        [sendMsgBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
        [timer invalidate];
    }
}

- (IBAction)registerBtn:(id)sender {
    
    if (![self validateParas]) {
        return ;
    }
    
    if (![self.telPhoneTF.text checkPhoneNumInput] ) {
        [MBProgressHUD showError:@"请输入正确的手机号码"];
        return;
    }
    
    NSMutableDictionary *para = [[NSMutableDictionary alloc] init];
    para[@"mobile"] = self.telPhoneTF.text;
    para[@"smsCode"] = self.msgCodeTF.text;
    para[@"password"] = self.passWdTF.text;
    
    [XYNetworking POST:@"api/register" baseURL:LYT_BASE_URL params:para success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *dict = (NSDictionary*)responseObject;
        if ([dict[@"code"] intValue] == 0) { 
            [self loginWithMobile:para[@"mobile"] password:para[@"password"]];
        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        [MBProgressHUD showError:@"请检查网络"];
    }];
}

- (void)loginWithMobile:(NSString *)mobile password:(NSString *)password{
    
    NSMutableDictionary *para = [[NSMutableDictionary alloc] init];
    para[@"mobile"] = mobile;
    para[@"password"] = password;
    
    [XYNetworking POST:@"api/login" baseURL:LYT_BASE_URL params:para success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *dict = (NSDictionary*)responseObject;
        if ([dict[@"code"] intValue] == 0) {
            //登陆成功,存下token到沙盒,跳转到主页
            [[NSUserDefaults standardUserDefaults] setObject:dict[@"token"] forKey:@"token"];
            [self restoreRootViewController:[[PGTabBarController alloc] init]];
        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        [MBProgressHUD showError:@"请检查网络"];
    }];
    
}

// 登陆后淡入淡出更换rootViewController
- (void)restoreRootViewController:(UIViewController *)rootViewController
{
    typedef void (^Animation)(void);
    UIWindow* window = [UIApplication sharedApplication].keyWindow;
    
    rootViewController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    Animation animation = ^{
        BOOL oldState = [UIView areAnimationsEnabled];
        [UIView setAnimationsEnabled:NO];
        [UIApplication sharedApplication].keyWindow.rootViewController = rootViewController;
        [UIView setAnimationsEnabled:oldState];
    };
    
    [UIView transitionWithView:window
                      duration:0.5f
                       options:UIViewAnimationOptionTransitionCrossDissolve
                    animations:animation
                    completion:nil];
}

- (IBAction)agreeProtocolBtnClick:(id)sender {
    UIButton *btn = (UIButton *)sender;
    btn.selected = !btn.selected;
    if (btn.selected) {
        self.registerBtn.enabled = true;
        [self.registerBtn setBackgroundColor:[UIColor colorWithRed:38/255.0 green:157/255.0 blue:63/255.0 alpha:1.0]];
    } else {
        self.registerBtn.enabled = false;
        [self.registerBtn setBackgroundColor:[UIColor lightGrayColor]];
    }
    
}

-(bool)validateParas {
    if ( self.telPhoneTF.text == nil || self.telPhoneTF.text.length == 0) {
        [MBProgressHUD showError:@"手机号不能为空!"];
        return NO;
    }
    if ( self.msgCodeTF.text == nil || self.msgCodeTF.text.length == 0) {
        [MBProgressHUD showError:@"验证码不能为空!"];
        return NO;
    }
    if ( self.passWdTF.text == nil || self.passWdTF.text.length == 0) {
        [MBProgressHUD showError:@"密码不能为空!"];
        return NO;
    }
    
    return YES;
}







@end
